var name = '';
var instance = null;
export class EventManager{
  constructor(){
    if (!instance) {
      instance = this;

      this.registerEventDispather = this.registerEventDispather.bind(this);
      this.getEventDispather = this.getEventDispather.bind(this);

      this.eventDispathers = {};
    }
    return instance;
  }

  //注册事件收发器
  registerEventDispather(name) {
      this.eventDispathers[name] = new EventDispatcher();
  }

  //获取事件收发器
  getEventDispather(name) {
    if(!this.eventDispathers[name]) {
        this.registerEventDispather(name);
    }
    return this.eventDispathers[name];
  }
}
new EventManager();
module.exports = instance;

export class EventDispatcher {
    constructor() {
        this.eventListeners = [];

        this.addEventListener = this.addEventListener.bind(this);
        this.removeEventListener = this.removeEventListener.bind(this);
        this.dispatcherEvent = this.dispatcherEvent.bind(this);
        this.clearEventListener = this.clearEventListener.bind(this);
    }

    //添加事件监听
    addEventListener(eventType, method) {
        this.eventListeners.push({eventType:eventType, method:method});
    }

    //移除事件监听
    removeEventListener(eventType, method) {
        var eventData = null;
        for(var i=0;i < this.eventListeners.length;i++) {
            eventData = this.eventListeners[i];
            if(eventData.eventType == eventType && eventData.method == method) {
                this.eventListeners.splice(i, 1);
                break;
            }
        }
    }

    //派发
    dispatcherEvent(event) {
        var eventData = null;
        for(var i=0;i < this.eventListeners.length;i++) {
            eventData = this.eventListeners[i];
            if(eventData.eventType == event.eventType) {
                eventData.method(event);
            }
        }
    }

    //清除所有监听
    clearEventListener() {
        this.eventListeners = [];
    }
}
